﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HitchHikersGuideToTheGalaxy.Models
{
    public class MessageRepository : HitchHikersGuideToTheGalaxy.Models.IMessageRepository
    {
        GalaxyDataContext db = new GalaxyDataContext();

        #region Add, Delete, Save

        /// <summary>
        /// Add one Message record to Database.
        /// </summary>
        /// <param name="message"></param>
        public void Add(Message message)
        {
            db.Messages.InsertOnSubmit(message);
        }

        /// <summary>
        /// Delete one Message record from Database.
        /// </summary>
        /// <param name="message"></param>
        public void Delete(Message message)
        {
            db.Messages.DeleteOnSubmit(message);
        }

        /// <summary>
        /// Save changes made to Database.
        /// </summary>
        public void Save()
        {
            db.SubmitChanges();
        }

        #endregion

        
        #region querys

        /// <summary>
        /// Find Message
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Message FindMessage(int id)
        {
            return db.Messages.SingleOrDefault(d => d.Id == id);
        }

        /// <summary>
        /// Fetch all Messages from Database.
        /// </summary>
        /// <returns></returns>
        public IQueryable<Message> FindAllMessages()
        {
            return db.Messages;
        }

        /// <summary>
        /// Fetch all Messages I have sent.
        /// </summary>
        /// <param name="mySSN"></param>
        /// <returns></returns>
        public IQueryable<Message> FindMessagesSentByMe(string mySSN)
        {
            return from m in db.Messages
                   where m.UserInfoSSNSender == mySSN
                   select m; 
        }

        /// <summary>
        /// Fetch all Messages I have recived.
        /// </summary>
        /// <param name="mySSN"></param>
        /// <returns></returns>
        public IQueryable<Message> FindMessagesSentToMe(string mySSN)
        {
            return from m in db.Messages
                   where m.UserInfoSSNReceiver == mySSN
                   select m;
        }

        /// <summary>
        /// Fetch all Messages I have sent to specific user.
        /// </summary>
        /// <param name="mySSN"></param>
        /// <param name="reciverSSN"></param>
        /// <returns></returns>
        public IQueryable<Message> FindMessagesSentByMeToUser(string mySSN, string reciverSSN)
        {
            return from m in db.Messages
                   where m.UserInfoSSNSender == mySSN
                   where m.UserInfoSSNReceiver == reciverSSN
                   select m;
        }

        #endregion

    }
}
